package com.example.demo.intercept;

import com.alibaba.fastjson.JSONObject;
import com.example.demo.tools.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author Administrator
 */
@Component
public class TimeStampIntercept implements HandlerInterceptor {
    @Autowired
    private RedisUtil redisUtil;

    /***
     * 返回错误信息
     */
    private void setReturn(HttpServletResponse response,
                           int status,
                           String msg) throws IOException {
        response.reset();
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter out = null;
        try {
            JSONObject res = new JSONObject();
            res.put("errno", status);
            res.put("errmsg", msg);
            res.put("curtime", System.currentTimeMillis());
            out = response.getWriter();
            out.append(res.toString());
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
            response.sendError(500);
        }
    }

    private boolean checkOverTime(Long timesStamp,
                                  Long curTime) {
        return (curTime - timesStamp) / (1000 * 60) > 2;
    }


    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        // if (("OPTIONS").equals(request.getMethod())) {
        //     response.setStatus(HttpStatus.NO_CONTENT.value());
        //     return true;
        // }

        String timesStampStr = request.getHeader("timestamp");
        if (!StringUtils.hasText(timesStampStr)) {
            setReturn(response, 20011, "timestamp不合法!");
            return false;
        }
        Long timesStamp = Long.valueOf(timesStampStr);
        Long curTime = System.currentTimeMillis();
        if (checkOverTime(timesStamp, curTime)) {
            setReturn(response, 20011, "timestamp不合法!");
            return false;
        }
        return true;
    }
}
